package com.ls.blog.security.handler;

import com.alibaba.fastjson.JSON;
import com.ls.blog.common.enums.ResultCode;
import com.ls.blog.dto.UserDetailsIml;
import com.ls.blog.entity.Log;
import com.ls.blog.entity.User;
import com.ls.blog.mapper.UserMapper;
import com.ls.blog.service.LogService;
import com.ls.blog.service.UserService;
import com.ls.blog.utils.ObjectUtils;
import com.ls.blog.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserMapper userMapper;

    @Autowired private LogService logService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        UserDetailsIml userDetailsIml = (UserDetailsIml) authentication.getPrincipal();
        //为了安全设置密码为null
        // 更新用户信息
        userDetailsIml.setPassword(null);
        updateUser(userDetailsIml);
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(R.ok(ResultCode.LOGIN_ok, userDetailsIml)));
    }

    /**
     * 异步更新或修改用户信息
     */
    public void updateUser(UserDetailsIml userDetailsIml){
        // 修改或更新用户
        User user = ObjectUtils.copyObject(userDetailsIml, User.class);
        user.setLastLoginTime(LocalDateTime.now());
        if (user.getId()==null){
            userMapper.insert(user);
        }else {
            userMapper.updateById(user);
        }
    }

}

